﻿//-----------------------------------------------------------------------
// <copyright>
// This file is subject to the terms and conditions of the Microsoft Public License (MS-PL).
// See http://www.microsoft.com/opensource/licenses.mspx#Ms-PL for more details.
// </copyright>
//----------------------------------------------------------------------- 
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;

namespace Fulcrum.WeakEventManager
{
    [Export(typeof(GenerationUnit))]
    public class WeakEventManagerGenerationUnit : GenerationUnit
    {
        WeakEventManagerSettings settings;
        List<GenerationDataContext> dataContexts;

        public WeakEventManagerGenerationUnit():
            base("WeakEventManager")
        {
            this.settings = new WeakEventManagerSettings();
            this.Settings = this.settings;
        }

        public override void CreateDataContexts()
        {
            var configReader = new WeakEventManagerGeneratorXmlConfiguration(this.settings.ConfigFileName);

            ProcessConfiguration(configReader);
        }

        protected void ProcessConfiguration(IWeakEventManagerGeneratorConfiguration configReader)
        {
            this.dataContexts = new List<GenerationDataContext>();

            foreach (var weakEventManager in configReader.WeakEventManagers)
            {
                if (String.IsNullOrEmpty(this.settings.WeakEventManager) ||
                    String.Equals(this.settings.WeakEventManager, weakEventManager.Name, StringComparison.OrdinalIgnoreCase))
                {
                    var dataContext = new WeakEventManagerGenerationDataContext(configReader, weakEventManager);
                    this.dataContexts.Add(dataContext);
                }
            }
        }

        public override ICollection<GenerationDataContext> DataContexts
        {
            get
            {
                return this.dataContexts;
            }
        }
    }
}
